package com.primestone.cim.util;


import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

/**
 * 
 * @author cesar.mateus
 *
 */
public class XMLUtil {

	/**
	 * Default constructor.
	 */
	public XMLUtil() {
		super();
	}

	/**
	 * pasa los parametros de un objeto a un archivo xml con el nombre de la clase y la extension xml
	 * @param obj
	 * @return
	 * @throws JAXBException
	 */
	public static byte[] marshall( Object obj ) throws JAXBException {
		ByteArrayOutputStream os = null;
		try {
			JAXBContext context = JAXBContext.newInstance( obj.getClass() );

			Marshaller m = context.createMarshaller();
			m.setProperty( Marshaller.JAXB_ENCODING, StringUtil.ENCODING_UTF8 );
			m.setProperty( Marshaller.JAXB_FORMATTED_OUTPUT, true );

			os = new ByteArrayOutputStream();

			m.marshal( obj, os );

			return os.toByteArray();
		} finally {
			if( os != null ){
				try {
					os.flush();
					os.close();
				} catch( IOException e ) {
					// Ignore.
				}

			}
		}
	}

	/**
	 * pasa un archivo xml a un objeto, la clase del objeto debe corresponder con la almacenada en el archivo
	 * @param xmlByteArray
	 * @param objectClass
	 * @return
	 * @throws JAXBException
	 */
	public static Object unmarchall( byte[] xmlByteArray, Class... objectClass ) throws JAXBException {
		ByteArrayInputStream is = null;
		try {
			is = new ByteArrayInputStream( xmlByteArray );

			JAXBContext jc = JAXBContext.newInstance( objectClass );
			Unmarshaller u = jc.createUnmarshaller();

			//Charset.defaultCharset()

			//u.setProperty( Marshaller.JAXB_ENCODING, StringUtil.ENCODING_UTF8 );
			//u.setProperty( Marshaller.JAXB_FORMATTED_OUTPUT, true );

			Object o = u.unmarshal( is );

			return o;
		} finally {
			if( is != null ){
				try {
					is.close();
				} catch( IOException e ) {
					// Ignore.
				}
			}
		}
	}
	
	/**
	 * @param object
	 * @param objectClass
	 * @param file
	 * @throws JAXBException
	 * @throws FileNotFoundException
	 */
	public static void unmarshall(Object object, Class objectClass, File file) throws JAXBException, FileNotFoundException {
		OutputStream fos = null;
		try {
			fos = new FileOutputStream(file);
			JAXBContext contextObj = JAXBContext.newInstance(objectClass);
			 
		    Marshaller marshallerObj = contextObj.createMarshaller();
		    marshallerObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
		 
		    marshallerObj .marshal(object, fos);
		} finally {
			if( fos != null ){
				try {
					fos.close();
				} catch( IOException e ) {
					// Ignore.
				}
			}
		}
		
	}

}
